<template>
	<view class="container">
		<block v-if="classList.length>0">
			<cp-goods-select height="92vh" :props="{label:'name',value:'id',children:'commodity'}" :options="classList"
				@scrolltolower="handelScrolltolower" @category-change="handelCategoryChange">
				<template v-slot:category>
					<cp-goods-select-category>
						<template v-for="(row,k) in classList">
							<cp-goods-category-item :key="item.id" :category="row">
								<text>{{row.name}}</text>
							</cp-goods-category-item>
						</template>
					</cp-goods-select-category>
				</template>
				<cp-goods-item v-for="(item,index) in classList" :key="item.id" :category="item.name">
					<u--text :text="item.name" bold margin="0 0 10rpx 0"></u--text>
					<view v-for="(cell,k) in item.commodity" :key="cell.id" class="goods__item ">
						<image src="@/static/logo.png" style="width: 180rpx;height: 180rpx;">
						</image>
						<view class="dis-flex list-desc">
							<view class="dis-flex justify-between">
								<u--text :text="cell.name"></u--text>
							</view>
							<u--text type="info" size="10" margin="0 0 6rpx 0" :text="cell.introduce"></u--text>
							<view class="money dis-flex justify-between">
								<text style="color: red;">￥{{cell.price||0}}</text>
								<uni-number-box v-model="cell.good_num" :min="0"></uni-number-box>
							</view>
						</view>
					</view>
				</cp-goods-item>
			</cp-goods-select>
		</block>
		<view style="height: 10vh;z-index: 1200;">
			<view class="bottom-navbar">
				<view class="dis-flex total-price">
					<view class="dis-flex" style="position: relative;width: 80rpx;height: 72rpx;"
						@click="showHiddenPopup">
						<u-icon name="bag" color="#fff" size="28"></u-icon>
						<text class="menu-length"> {{totalShopLength}} </text>
					</view>
					<view style="margin-left: 10rpx;font-weight: 600;">￥{{totalMoney}}</view>
				</view>
				<button class="submit" @click="openRemarkPopup">下单</button>
			</view>
		</view>
		<uni-popup ref="popup" type="bottom" background-color="#fff">
			<view class="popup-style">
				<uni-section class="mb-10" title="购物车">
					<template v-slot:right>
						<u--text suffixIcon="trash" iconStyle="font-size: 18px" type="info" @click="cleanSelectList"
							text="清空购物车"></u--text>
					</template>
				</uni-section>
				<view class="popup-scroll">
					<view v-for="(cell,k) in selectList" :key="cell.id" class="goods__item ">
						<image :src="cell.goods_front_image_url" style="width: 80rpx;height: 80rpx;">
						</image>
						<view class="dis-flex list-desc">
							<u--text :text="cell.name"></u--text>
							<u--text type="info" size="10" margin="0 0 6rpx 0" :text="cell.introduce"></u--text>
							<view class="money dis-flex justify-between">
								<text style="color: red;">￥{{cell.good_price||0}}</text>
								<uni-number-box v-model="cell.good_num" :min="0"
									@change="bindChangeGoodNum(cell)"></uni-number-box>
							</view>
						</view>
					</view>
				</view>
				<view style="height: 8vh;">
					<view class="bottom-navbar">
						<view class="dis-flex total-price">
							<view class="dis-flex" style="position: relative;width: 80rpx;height: 72rpx;"
								@click="showHiddenPopup">
								<u-icon name="bag" color="#fff" size="28"></u-icon>
								<text class="menu-length"> {{totalShopLength||0}} </text>
							</view>
							<view style="margin-left: 10rpx;font-weight: 600;">￥{{totalMoney||0}}</view>

						</view>
						<button class="submit" @click="openRemarkPopup">下单</button>
					</view>
				</view>
			</view>
		</uni-popup>
		<!-- 弹窗 -->
		<u-popup :show="showRemarkPopup" mode="center" :round="10" @close="closeRemarkPopup" closeable
			@open="openRemarkPopup" :safeAreaInsetBottom="false" bold>
			<view style="padding: 20rpx;width: 500rpx;">
				<u-text text="我的地址" bold align="center" margin="30rpx 0"></u-text>
				<uni-forms ref="form" :modelValue="formData" :rules="rules">
					<uni-forms-item label="单元" name="floor">
						<uni-easyinput v-model="formData.floor" placeholder="请输入单元"></uni-easyinput>
					</uni-forms-item>
					<uni-forms-item label="楼层" name="tower">
						<uni-easyinput v-model="formData.tower" placeholder="请输入楼层"></uni-easyinput>
					</uni-forms-item>
					<uni-forms-item label="房间" name="room">
						<uni-easyinput v-model="formData.room" placeholder="请输入房间"></uni-easyinput>
					</uni-forms-item>
				</uni-forms>
				<view class="dis-flex" style="width: 60%;margin: auto;">
					<button @click="closeRemarkPopup" size="mini" style="margin: 30rpx 30rpx 0 0; ">取消</button>
					<button @click="submit" size="mini" style="margin: 30rpx 0 0 0;background: #ffd100;">提交</button>
				</view>

			</view>
		</u-popup>
		<u-loading-page loading-mode="semicircle" :loading="showLoading"></u-loading-page>
	</view>

</template>

<script>
	import {
		buyProductApi,
		getGoodsListApi,
		getShopDetailApi,
		addOrderApi,
		getShopClassListApi,
		getShopClassDetailListApi
	} from '@/api/index.js'
	export default {
		components: {

		},
		data() {
			return {
				showLoading: false,
				page: 1, // 当前页码
				pageSize: 15, // 每页显示的商品数量
				total: 0, // 总商品数量
				list: [{
					id: 1,
					name: '酒水',
					good_list: {
						id: 1,
						"name": "牛肉丸"
					}
				}],
				goods: [],
				selectList: [],
				showRemarkPopup: false, //下单备注弹窗
				orderRemark: "",
				classList: [],
				formData: {
					business: "",
					floor: "",
					room: "",
					tower: ""
				},
				rules: {
					floor: {
						floor: [{
							required: true,
							errorMessage: '请输入单元',
						}, ]
					},
					tower: {
						rules: [{
							required: true,
							errorMessage: '请输入楼层',
						}]
					},
					room: {
						rules: [{
							required: true,
							errorMessage: '请输入房间',
						}]
					}
				},

			}
		},
		onLoad(options) {
			console.log(options.id);
			this.formData.business = options.id;
			this.getShopClassList(options.id)
		},
		computed: {
			// 计算商品数量
			totalShopLength() {
				return this.classList
					.map(item => {
						// 检查item.commodity是否为空
						if (!item.commodity || item.commodity.length === 0) {
							return 0;
						}
						return item.commodity.reduce((sum, goodsItem) => {
							const num = parseFloat(goodsItem.good_num);
							return isNaN(num) ? sum : sum + num;
						}, 0);
					})
					.reduce((total, num) => total + num, 0);
			},
			// 计算总金钱
			totalMoney() {
				let totalPrice = 0;
				if (this.classList.length > 0) {
					this.classList.forEach(item => {
						if (item.commodity && item.commodity.length > 0) {
							// console.log(item.commodity);
							item.commodity.forEach(goodsItem => {
								const num = parseFloat(goodsItem.good_num);
								const price = parseFloat(goodsItem.price);
								if (!isNaN(num) && !isNaN(price)) {
									totalPrice += num * price;
								}
							});
						}
					});
				}
				return parseFloat(totalPrice.toFixed(2));
			},
			// 购物车中的商品
			selectedShopList() {
				let selectedShopItem = []
				this.classList.forEach(item => {
					if (item.commodity && item.commodity.length > 0) {
						item.commodity.map(goodsItem => {
							const num = parseFloat(goodsItem.good_num);
							if (num > 0) {
								selectedShopItem.push({
									name: goodsItem.name,
									good_num: goodsItem.good_num,
									id: goodsItem.id,
									good_price: goodsItem.price,
									goods_front_image_url: goodsItem.goods_front_image_url
								})
							}
						});
					}

				})
				this.selectList = selectedShopItem
				if (selectedShopItem.length === 0) {
					// 调用关闭popup的方法
					this.$nextTick(() => {
						this.$refs.popup.close()
					})
				}
				return selectedShopItem
			},
		},
		methods: {
			initList() {
				let result = []
				let i = 0
				while (++i < 20) {
					let children = []
					let j = 0
					while (++j < 10) {
						children.push({
							label: '商品' + j,
							value: j,
						})
					}
					result.push({
						label: '分类' + i,
						value: i,
						children: children
					})
				}
				return result
			},
			// 商家商品
			async getShopDetail(business) {
				const {
					data: res
				} = await getShopDetailApi({
					business
				})
				this.classList = res.class;
				console.log(res);
			},
			async getShopClassList(business) {
				const {
					data: res
				} = await getShopClassListApi({
					business
				})
				this.classList = res.class;
				for (var i = 0; i < res.class.length; i++) {
					console.log(res.class[i]);
					this.getShopClassDetailList(res.class[i].id, res.class[i].business)
				}
				console.log(res);
			},
			async getShopClassDetailList(cate, business) {
				const {
					data: res
				} = await getShopClassDetailListApi({
					class: cate,
					business,
					page: this.page
				})
				console.log(res);
			},

			handelScrolltolower(e) {
				console.log('handelScrolltolower', e)
			},

			handelCategoryChange(e) {
				console.log('handelCategoryChange', e)
			},

			async showHiddenPopup() {
				const result = await this.isHasGood()
				console.log(result);
				if (result) {
					this.$refs.popup.open()
				}
			},
			isHasGood() {
				if (this.totalShopLength <= 0) {
					uni.showToast({
						title: '请先选择商品',
						icon: 'error'
					})
					return false
				} else {
					return true
				}
			},
			// 清空购物车
			cleanSelectList() {
				uni.showModal({
					title: '提示',
					content: '您确定要清空购物车吗',
					success: (res) => {
						if (res.confirm) {
							this.clearSelectList();
						}
					}
				})
			},
			// 清空数据
			clearSelectList() {
				this.classList.forEach(item => {
					if (item.commodity && item.commodity.length > 0) {
						item.commodity.forEach(goodsItem => {
							goodsItem.good_num = 0;
						});
					}
				});
				this.selectList = []
				this.$refs.popup.close()
			},
			// 点击popup步进器，外部也更新
			bindChangeGoodNum(good) {
				setTimeout(() => {
					this.list.forEach(item => {
						item.good_list.forEach(goodsItem => {
							if (good.id === goodsItem.id) {
								this.$set(goodsItem, 'good_num', good.good_num);
							}
						});
					});
				}, 0);
			},
			// 打开下单备注弹窗
			async openRemarkPopup() {
				const result = await this.isHasGood()
				if (result) {
					this.showRemarkPopup = true;
				}
			},
			// 关闭
			closeRemarkPopup() {
				this.formData = {};
				this.clearSelectList();
				this.showRemarkPopup = false;
			},
			// 提交
			submit() {
				this.$refs.form.validate().then(res => {
					this.addOrder()
				}).catch(err => {})
			},
			// 下单
			async addOrder() {
				const {
					totalMoney
				} = this;
				const {
					business,
					floor,
					room,
					tower
				} = this.formData
				const order_commodity = this.selectList.map((item => {
					return {
						num: item.good_num,
						price: item.good_price
					}
				}))
				let params = {
					business,
					tower,
					floor,
					room,
					price: totalMoney,
					order_commodity,
				}
				const {
					data: res
				} = await addOrderApi(params)
				console.log(res);
				if (res.state === true) {
					uni.showToast({
						title: '下单成功'
					})
					this.closeRemarkPopup()
				} else {
					uni.showToast({
						title: '下单失败',
						icon: 'error'
					})
				}
			},

		}
	}
</script>

<style lang="scss">
	//小程序需要实现商品样式
	.cp-goods-select-goods__item {
		padding: 30upx;
		box-sizing: border-box;
		background-color: #ffffff;
		border-radius: 4px;
		font-size: 14px;
		color: #262626;
		margin-bottom: 10upx;

		.sub-info {
			font-size: 12px;
			color: #84898f;
		}
	}

	.content {
		background-color: #eceff5;
		height: 100%;
	}

	.goods__item {
		height: 200rpx;
		display: flex;
		align-items: center;
		padding: 20rpx !important;

		image {
			width: 180rpx;
			height: 180rpx;
			border-radius: 15rpx;
		}

		.list-desc {
			flex-direction: column;
			justify-content: space-between;
			padding-left: 10rpx;
			flex: 1;
		}

		.money {
			font-size: 30rpx;
			font-weight: 600;
			display: flex;
			align-items: center;
		}
	}

	.logo {
		height: 200rpx;
		width: 200rpx;
		margin-top: 200rpx;
		margin-left: auto;
		margin-right: auto;
		margin-bottom: 50rpx;
	}

	.text-area {
		display: flex;
		justify-content: center;
	}

	.title {
		font-size: 36rpx;
		color: #8f8f94;
	}

	.item {
		padding: 10upx 30upx;
		background-color: #fff;
		margin: 0 10upx;
		margin-bottom: 10upx;

	}

	.num {
		border-radius: 50%;
		background-color: #ffd100;
		color: #fff;
		display: inline-block;
		width: 30upx;
		height: 30upx;
		line-height: 30upx;
		text-align: center;
		position: absolute;
		top: 4px;
		font-size: 16rpx;
		box-sizing: border-box;
	}

	.bottom-navbar {
		position: fixed;
		bottom: 20px;
		width: 100%;
		height: 100rpx;
		// border-radius: 50rpx 50rpx 0 0;
		background-color: #262626;
		display: flex;
		align-items: center;
		justify-content: space-between;
		color: #fff;
		font-size: 36rpx;

		.menu-length {
			border-radius: 50%;
			background: #ffd100;
			color: #000;
			width: 30rpx;
			display: inline-block;
			height: 30rpx;
			line-height: 30rpx;
			text-align: center;
			font-size: 18rpx;
			box-sizing: border-box;
			position: absolute;
			top: 0rpx;
			right: 3rpx;

		}

		.total-price {
			align-items: center;
			padding-left: 50rpx;

		}

		.submit {
			background: #ffd100;
			margin: 0;
			height: 100rpx;
			width: 250rpx;
			font-weight: 600;
			font-size: 32rpx;
			color: #000;
			line-height: 100rpx;
			// border-radius: 0 50rpx 0rpx 0;
			border-radius: 0;
		}
	}

	.uni-section-header__content {
		font-size: 30rpx;
		font-weight: 600;
	}

	.popup-style {
		max-height: 60vh;
		display: flex;
		flex-direction: column;

		.popup-scroll {
			flex: 1;
			overflow-y: scroll;
		}
	}
</style>